package com.quan.commons.utils;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 树状菜单工具类
 *
 * @author yhaoquan
 */
public class MenuTreeUtil {

    public static Map<String, Object> mapArray = new LinkedHashMap<String, Object>();

    public List<MenuTreeNode> menuCommon;
    public List<Object> list = new ArrayList<Object>();

    public List<Object> treeMenu(List<MenuTreeNode> menu) {
        this.menuCommon = menu;
        for (MenuTreeNode node : menu) {
            Map<String, Object> mapArr = new LinkedHashMap<String, Object>();
            if (node.getPid() == -1) {
                setTreeMap(mapArr, node);
                list.add(mapArr);
            }
        }
        return list;
    }

    public List<?> menuChild(Integer id) {
        List<Object> lists = new ArrayList<Object>();
        for (MenuTreeNode a : menuCommon) {
            Map<String, Object> childArray = new LinkedHashMap<String, Object>();
            if (a.getPid() == id) {
                setTreeMap(childArray, a);
                lists.add(childArray);
            }
        }
        return lists;
    }

    private void setTreeMap(Map<String, Object> mapArr, MenuTreeNode node) {
        // 可追加其他属性
        mapArr.put("id", node.getId());
        mapArr.put("name", node.getName());
        mapArr.put("pid", node.getPid());
        List<?> childrens = menuChild(node.getId());
        if (childrens.size() > 0) {
            mapArr.put("hasChild", true);
        } else {
            mapArr.put("hasChildren", false);
        }
        mapArr.put("children", menuChild(node.getId()));
    }

    public static void main(String[] args) {

        List<MenuTreeNode> treeNodes = new ArrayList<>();
        MenuTreeNode MenuTreeNode1 = new MenuTreeNode(1, -1, "首页");
        MenuTreeNode MenuTreeNode2 = new MenuTreeNode(2, -1, "订单");
        MenuTreeNode MenuTreeNode3 = new MenuTreeNode(3, 1, "预约");
        MenuTreeNode MenuTreeNode4 = new MenuTreeNode(4, 2, "捐献");
        MenuTreeNode MenuTreeNode5 = new MenuTreeNode(5, 4, "我的订单");
        MenuTreeNode MenuTreeNode6 = new MenuTreeNode(6, 5, "个人中心");
        MenuTreeNode MenuTreeNode7 = new MenuTreeNode(7, 6, "个人中心2");
        MenuTreeNode MenuTreeNode8 = new MenuTreeNode(8, 99, "个人中心3");
        treeNodes.add(MenuTreeNode1);
        treeNodes.add(MenuTreeNode6);
        treeNodes.add(MenuTreeNode5);
        treeNodes.add(MenuTreeNode3);
        treeNodes.add(MenuTreeNode4);
        treeNodes.add(MenuTreeNode2);
        treeNodes.add(MenuTreeNode7);
        treeNodes.add(MenuTreeNode8);

        MenuTreeUtil treeUtil = new MenuTreeUtil();
        System.out.print(JSON.toJSONString(treeUtil.treeMenu(treeNodes)));

    }

}
